/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller.bjxxclassnaterialfile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialProject;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.IBjxxClassMaterialFileService;
import cn.qidisoft.edu.hzjt.service.IBjxxClassMaterialProjectService;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hhl
 * @version $Id: ProjectController.java, v 0.1 2018年10月23日 下午4:56:53 hhl Exp $
 */
@Controller
@RequestMapping(value = "bjxxClassMaterialFile")
public class BjxxClassMaterialFileController {
    protected static final LoggerAdapter                    LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);
    @Autowired
    private IBjxxClassMaterialFileService                   bjxxClassMaterialFileService;

    private static String                                   upload = null;

    @Autowired
    private IBjxxClassMaterialProjectService                bjxxClassMaterialProjectService;
    @Autowired
    private ICommonService                                  commonService;

    private static Map<String, List<BjxxClassMaterialFile>> picMap = new HashMap<String, List<BjxxClassMaterialFile>>();

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "gid", required = false) String gid,
                          @RequestParam(value = "rangeId", required = false) String rangeId) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            picMap.remove(String.valueOf(userEmployee.getUserid()));

            BjxxClassMaterialProject data = new BjxxClassMaterialProject();
            data.setXmid(id);
            data.setGid(gid);
            data.setRangeId(Integer.valueOf(rangeId));
            data = bjxxClassMaterialProjectService.queryByPK_bzr(data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if (data.getIssuetime() == null) {
            } else {
                data.setIssuetime1(sdf.format(data.getIssuetime()));
            }

            if (data.getDeadline() == null) {
            } else {
                data.setDeadline1(sdf.format(data.getDeadline()));
            }
            model.addAttribute("data", data);

            BjxxClassMaterialFile data1 = new BjxxClassMaterialFile();
            data1.setRangeid(Integer.valueOf(rangeId));
            List<BjxxClassMaterialFile> dataList = bjxxClassMaterialFileService.queryList(data1);
            model.addAttribute("dataList", dataList);

            return "bjxxClassMaterialProject/detailsBjxxClassMaterialProject_bzr";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加目录信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /**
     * 新增删除
     * 
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {

        List<BjxxClassMaterialFile> list = new ArrayList<BjxxClassMaterialFile>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
            .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<BjxxClassMaterialFile> docFileResourceList = picMap
            .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;

        BjxxClassMaterialFile docFile = new BjxxClassMaterialFile();
        if (!file.isEmpty()) {
            // 文件的大小
            docFile
                .setFilesize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));

            String name = file.getOriginalFilename();// 获取上传文件名
            docFile.setFilename(name);
            String gid = UUID.randomUUID().toString();
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            // 文件路径带后缀
            docFile.setFilepath(gid + "/" + gid + "." + extend);
            // 全路径系统文件名称带点
            docFile
                .setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
            // 文件名称uuid
            docFile.setFilename(gid);
            // 上传时间
            docFile.setMsubmittime(new Date());
            // 获取文件类型
            docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
            docFile
                .setFilesize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));// 获取文件大小
            // uuid
            docFile.setGid(gid);

            docFile.setMufile(file);
            try {
                docFile.setInputStream(file.getInputStream());
            } catch (IOException e) {
            }

            if (docFileResourceList != null && docFileResourceList.size() > 0) {
                docFileResourceList.add(docFile);
                picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
            } else {
                list.add(docFile);
                picMap.put(String.valueOf(userEmployee.getUserid()), list);
            }
            LOGGER.info("附件上传成功！");
        }
        PrintWriter writer = null;
        try {

            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilepath());
            // 文件名称
            docFile2.setFilename(docFile.getFilename());
            docFile2.setSysfilepath(docFile.getSysfilepath());

            writer = (PrintWriter) response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增删除服务器的文件
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            // env配置路径
            String path = upload;

            String filepath = request.getParameter("filepath");
            LOGGER.info("文件的原始路径===" + filepath);
            // 文件的全路径
            String fullpath = null;
            // 文件名称
            String filename = null;
            // 文件名无后缀
            String fileNoSuffix = null;

            if (filepath.indexOf("prefix") == -1) {
                // 文件的文件名称
                fileNoSuffix = filepath.split(",")[0];
                String sec = filepath.split(",")[1];
                // 文件的后缀
                String suffix = sec.substring(sec.indexOf("."));
                // 文件名无后缀加上后缀
                filename = fileNoSuffix + suffix;
                // 文件的全路径
                fullpath = path + "/" + fileNoSuffix;
                // FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
                // FileUtils.forceDelete(new File(fullpath)); //删除文件目录
            } else {
                return dataMap;
            }

            List<BjxxClassMaterialFile> noticeNewsFilepathList = picMap
                .get(String.valueOf(userEmployee.getUserid()));

            // 删除list里面前台删除的前台信息图片附件表
            if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
                for (BjxxClassMaterialFile noticenewsfilepath : noticeNewsFilepathList) {
                    if (noticenewsfilepath.getFilename().equals(fileNoSuffix)) {
                        noticeNewsFilepathList.remove(noticenewsfilepath);
                        break;
                    }
                }
            }
            // 先删除
            picMap.remove(userEmployee.getUserid());
            // 后添加
            picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
            dataMap.put("success", "0000");
            return dataMap;
        } catch (Exception e) {
            dataMap.put("success", "-9999");
            return dataMap;
        }
    }

    @SysLogger(description = "班主任提交材料管理", moduleName = "班主任提交材料管理", method = "新增")
    @RequestMapping(value = "/Save", method = RequestMethod.POST)
    public String Save(ModelMap model, HttpServletRequest request, BjxxClassMaterialFile data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            String path = upload;
            List<BjxxClassMaterialFile> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                for (BjxxClassMaterialFile r : docFileResourceList) {
                    file = r.getMufile();
                    r.setProjectid(data.getProjectid());
                    r.setEmpid(userEmployee.getEmid());
                    r.setRangeid(data.getRangeid());
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = path + File.separator + r.getGid();
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);

                    r.setGid(r.getGid());// 附件id
                    r.setFilename(name);
                    bjxxClassMaterialFileService.add(r);
                }
            }
            return "redirect:/bjxxClassMaterialProject/index_bzr";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /**
     * 修改删除图片
     * 
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("id") String id,
                                                                  HttpServletRequest request,
                                                                  HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            BjxxClassMaterialFile data = new BjxxClassMaterialFile();
            data.setGid(id);
            bjxxClassMaterialFileService.delete(data);
            File file = new File(upload + File.separator + id);
            if (file.isDirectory()) {// 判断file是否是文件目录 若是返回TRUE
                String name[] = file.list();// name存储file文件夹中的文件名
                for (int i = 0; i < name.length; i++) {
                    File f = new File(upload + File.separator + id, name[i]);// 此时就可得到文件夹中的文件
                    f.delete();// 删除文件
                }
                FileUtils.forceDelete(new File(upload + File.separator + id)); // 最后删除文件目录
            }
            dataMap.put("success", "0000");
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("success", "-9999");
        }
        return dataMap;
    }

}
